import os
from dotenv import load_dotenv
from typing import Union


class ConfigLoader:
    def __init__(self):
        load_dotenv()
    
    def get(self, key: str,
            default: Union[str, int, bool, None] = None
            ) -> Union[str, int, bool]:
        """获取配置项并自动转换类型"""
        value = os.getenv(key, default)
        
        if value is None:
            raise ValueError(
                f"Configuration '{key}' not found and no default provided"
            )
            
        # 先尝试识别bool字符串
        if isinstance(value, str):
            val_lower = value.lower()
            if val_lower in ('true', 'false', 'yes', 'no', '1', '0'):
                return val_lower in ('true', 'yes', '1')
        
        # 根据default参数类型转换
        if isinstance(default, bool):
            return bool(value)
        elif isinstance(default, int):
            return int(value)
        return str(value)


# 创建全局配置加载器实例
config = ConfigLoader()